<?php
namespace app\api\controller\newfile;

use think\Controller;
use think\Request;
use app\common\model\power\Rolepower;
use app\common\model\newmodel\User as UserModel;
use app\common\model\newmodel\Contract as ContractModel;
use app\api\controller\Pub;
use app\api\controller\Base;
use think\facade\Env;
use app\common\model\newmodel\ContractOrder;
use app\api\controller\newfile\Orders;
use think\facade\Cache;
class Contract extends Base
{
    public function initialize(){
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(401002);
	}

    /**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login(){
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}
    
    /**
     * 合同列表
     */
    public function contractList()
    {
        $page = input('page') ?? 1;
        $pageSize = input('pageSize') ?? 10;
        $keyword = input('keyword') ?? '';
        
        $userId = Pub::userid();
        $result = ContractModel::getContractList($userId, $page, $pageSize, $keyword);
        return json($result);
    }

    //获取合同编号
    public static function getCurrentContractNumber()
    {
        $date = date('Ymd');
        $cacheKey = 'contract_number_' . $date;
        
        // 从缓存获取当前编号，默认1
        $currentNum = Cache::get($cacheKey, 1);
        
        // 格式化编号，确保是4位数字
        $formattedNum = str_pad($currentNum, 4, '0', STR_PAD_LEFT);
        
        $contractNumber= 'PC-'.$date . '-' . $formattedNum;
        return myok($contractNumber);
    }
    
    /**
     * 递增合同编号（在合同添加成功后调用）
     */
    private static function incrementContractNumber()
    {
        $date = date('Ymd');
        $cacheKey = 'contract_number_' . $date;
        
        // 从缓存获取当前编号，默认1
        $currentNum = Cache::get($cacheKey, 1);
        
        // 编号加1
        $newNum = $currentNum + 1;
        
        // 保存到缓存，设置过期时间为当天23:59:59
        $expireTime = strtotime(date('Y-m-d 23:59:59')) - time();
        Cache::set($cacheKey, $newNum, $expireTime);
        
        return $newNum;
    }
    
    /**
     * 添加合同
     */
    public function contractAdd()
    {
        $data = input('post.');
        if (empty($data['customer_id']) || empty($data['contract_name'])) {
            return ['code' => 0, 'msg' => '客户ID和合同名称不能为空'];
        }
    
         $files = request()->file('img');

            if (!empty($files)) {
                $imgUrls = [];
                // 循环处理每个上传的文件
                foreach ($files as $file) {
                    $res = $this->upimg($file); // 传入单个文件对象
                    $res = (array)json_decode($res);
                    if ($res['status'] == 'ok') {
                        $imgUrls[] = $res['data'];
                    } else {
                        return ['code' => 0, 'msg' => '图片上传失败: ' . $res['data']];
                    }
                }
                // 将多个图片URL用逗号分隔存储，或根据需要改为JSON格式
                $data['img_url'] = implode(';', $imgUrls);
            }
        $result = ContractModel::addContract($data);
        self::incrementContractNumber();
        return json($result);
    }
    

    //添加合同同时生成订单
    public function contractOrder()
    {
        $data = input();
        if (empty($data['customer_id']) || empty($data['contract_name'])) {
            return ['code' => 0, 'msg' => '客户ID和合同名称不能为空'];
        }
        
        // 处理图片上传（如果需要）
        if (request()->file('img')) {
            $res = $this->upimg();
            $res = (array)json_decode($res);
            $data['img_url'] = $res['data'];
        }
        $result = ContractModel::addContract($data);
        $contract_id=$result['data'];
        
        return myok($result);
    }

    /**
     * 修改合同
     */
    public function contractEdit()
    {
        $file = request()->file('img');
        $data = input('post.');
        if ($file) {
            $res = $this->upimg();
            $res = (array)json_decode($res);
            $data['img_url'] = $res['data'];
        }
        $result = ContractModel::editContract($data);
        return json($result);
    }

    
     //合同删除
    public function contractDel()
    {
        $id = input('id');
        if (empty($id)) {
            return json(['code'=>0, 'msg'=>'参数不完整']);
        }
        $contract=ContractModel::get($id);
        if(!$contract){
            return json(['code'=>0, 'msg'=>'合同不存在']);
        }
        $contract->State=3;
        $contract->save();
        return json(['code'=>1, 'msg'=>'删除成功']);
    }

    //上传合同凭证
    public function upimg(\think\File $file){
		$type = empty(input('type')) ? 'other' :input('type');
		if(!$type=='hawa'||!$type=='buss'||!$type=='acco' || !$type=='product'){
			$type = 'other';
		}
		
        // 移动到框架应用根目录/public/uploads/ 目录下
        if(!is_null($file)){
           	try{
           		$save_path = Env::get('root_path').'public\\static' .'\\upimg\\countract\\'.$type.'\\';
	            $info = $file->validate(["size"=>50000000,'ext'=>'jpg,png,gif'])->rule("date")->move($save_path);
	            //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
	            $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
	            $image->thumb(2000, 2000)->save($save_path .  '\\' . $info->getSaveName());
	            if($info){//getSaveName();
	                $p=$info->getFilename();
	                return json_encode(['status'=>'ok','data'=>'http://192.168.10.127:8081/'.'static/upimg/countract/'.$type.'/'.date('Ymd',time()).'/'.$p]);
	            }else{
	              return json_encode(['status'=>'error','data'=>$info->getError()]);
	            }
           	} catch (\Exception $e) {
				return json_encode(['status'=>'error','data'=>$e->getMessage()]);
			}

         }else{
              return json_encode(['status'=>'error','data'=>'没有找到需要上传的图片']);
         }
	}
    
    /*
    public static function generate()
    {
        // 获取当前日期
        $date = date('Ymd');
        $cacheKey = 'contract_number_' . $date;
        
        // 尝试从缓存获取当前编号
        $currentNum = Cache::get($cacheKey);
        
        // 如果缓存中没有或已过期，初始化编号为1
        if ($currentNum === false) {
            $currentNum = 1;
        } else {
            // 编号加1
            $currentNum++;
        }
        
        // 保存到缓存，设置过期时间为当天23:59:59
        $expireTime = strtotime(date('Y-m-d 23:59:59')) - time();
        Cache::set($cacheKey, $currentNum, $expireTime);
        
        // 格式化编号，确保是4位数字
        $formattedNum = str_pad($currentNum, 4, '0', STR_PAD_LEFT);
        
        // 组合并返回合同编号
        return $date . '-' . $formattedNum;
    }
    
    public function contractAdd()
    {
        $data = input('post.');
        if (empty($data['customer_id']) || empty($data['contract_name'])) {
            return ['code' => 0, 'msg' => '客户ID和合同名称不能为空'];
        }
        
        // 处理图片上传（如果需要）
        if (request()->file('img')) {
            $res = $this->upimg();
            $res = (array)json_decode($res);
            $data['img_url'] = $res['data'];
        }
        $result = ContractModel::addContract($data);
        return json($result);
    }
    */
}
